package com.linshuo.employee.controller;

import com.linshuo.employee.entity.User;
import com.linshuo.employee.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.saveUser(user);
    }

    @PreAuthorize("hasRole('ADMIN') or #id == principal.username")
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user, Authentication authentication) {
        // 员工只能改自己，管理员可改所有
        if (!authentication.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))) {
            User current = userService.getUserByIdCard(authentication.getName());
            if (!current.getId().equals(id)) {
                throw new RuntimeException("无权操作");
            }
        }
        user.setId(id);
        return userService.updateUser(user);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }

    @PreAuthorize("hasRole('ADMIN') or #id == principal.username")
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id, Authentication authentication) {
        // 员工只能查自己，管理员可查所有
        if (!authentication.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))) {
            User current = userService.getUserByIdCard(authentication.getName());
            if (!current.getId().equals(id)) {
                throw new RuntimeException("无权操作");
            }
        }
        return userService.getUserById(id);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
} 